<template>
    <div class="generation-view">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>图文生成</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="tabs">
            <el-radio-group v-model="generationType" @change="setGenerationType">
                <el-radio-button :value="0">文案生成</el-radio-button>
                <el-radio-button :value="1">图片生成</el-radio-button>
                <el-radio-button :value="2">文案优化</el-radio-button>
            </el-radio-group>
        </div>

        <div class="content-wrapper">
            <div class="input-panel">
                <div class="form-container">
                    <el-form label-position="top">
                        <el-form-item label="文案主题">
                            <el-input v-model="contentTheme" placeholder="请输入您要生成的文案主题" type="textarea"
                                :autosize="{ minRows: 8 }" resize="none" class="theme-input tall-textarea" clearable
                                :disabled="isGenerating" />
                        </el-form-item>
                    </el-form>

                    <div class="action-buttons">
                        <el-button type="primary" @click="startCreation" class="primary-button" :loading="isGenerating">
                            开始创作
                        </el-button>
                        <el-button @click="clearContent" :disabled="isGenerating">
                            清空内容
                        </el-button>
                    </div>
                </div>
            </div>

            <div class="divider"></div>

            <div class="output-panel">
                <div class="output-header">
                    <el-button style="color: #333" @click="clearGeneratedCopy"
                        :disabled="!generatedCopy || isGenerating">
                        <el-icon>
                            <Plus />
                        </el-icon> 新建
                    </el-button>
                    <el-button type="primary" @click="copyToClipboard" :disabled="!generatedCopy || isGenerating">
                        复制文案
                    </el-button>
                </div>

                <div class="output-content">
                    <el-empty v-if="!generatedCopy"
                        :description="isGenerating ? '正在生成文案，请稍候...' : `填写左侧内容并点击'开始创作'生成文案`">
                        <template v-if="isGenerating" #image>
                            <el-icon class="is-loading" style="font-size: 40px; color: #409EFF;">
                                <el-icon-loading />
                            </el-icon>
                        </template>
                    </el-empty>
                    <div v-else class="copy-preview">
                        <div class="copy-content">{{ generatedCopy }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Loading as ElIconLoading } from '@element-plus/icons-vue'
import { useSidebarStore } from '../../../stores/sidebar'
import { ElMessage } from 'element-plus'

const router = useRouter()
const sidebarStore = useSidebarStore()
const generationType = computed(() => sidebarStore.generationType)

watch(() => sidebarStore.generationType, (newVal) => {
    const paths = ['/media/text-gen', '/media/image-gen', '/media/copy-opt']
    router.push(paths[newVal])
})

const setGenerationType = (type) => {
    sidebarStore.setGenerationType(type)
}

const contentTheme = ref('')
const generatedCopy = ref(null)
const isGenerating = ref(false)

const startCreation = async () => {
    if (!contentTheme.value || contentTheme.value.trim() === '') {
        ElMessage.warning('请输入文案主题')
        return
    }

    generatedCopy.value = ''
    isGenerating.value = true

    try {
        const response = await fetch('https://api.coze.cn/open_api/v2/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer pat_aJkBQ3bdzXNqFW5hWPBCYDno1uKHIB7H31FlauqkIzcYjyGPDW1PLB3yhPMJIDUO',
            },
            body: JSON.stringify({
                bot_id: '7514604779898404873',
                user: "123456",
                query: `生成文案，主题：${contentTheme.value}`,
                variables: {
                    text: `请生成一段关于"${contentTheme.value}"的文案`,
                    prompt: contentTheme.value
                },
                stream: false,
            }),
        })

        if (!response.ok) {
            throw new Error('请求失败，状态码：' + response.status)
        }

        const result = await response.json()

        const answerMsg = result.messages.find(m => m.type === 'answer')
        if (answerMsg) {
            generatedCopy.value = answerMsg.content
            return
        }

        const toolMsg = result.messages.find(m => m.type === 'tool_response')
        if (toolMsg) {
            const toolData = JSON.parse(toolMsg.content)
            generatedCopy.value = toolData.output || toolData.output1 || '未获取到有效内容'
            return
        }

        throw new Error('API返回数据格式不符合预期')

    } catch (error) {
        console.error('生成失败:', error)
        ElMessage.error(`文案生成失败: ${error.message}`)
        generatedCopy.value = `生成失败: ${error.message}\n您可以尝试重新生成或检查输入内容。`
    } finally {
        isGenerating.value = false
    }
}

const clearContent = () => {
    contentTheme.value = ''
    selectedModel.value = models[0]
}

const clearGeneratedCopy = () => {
    generatedCopy.value = null
}

const copyToClipboard = async () => {
    if (!generatedCopy.value) return

    try {
        await navigator.clipboard.writeText(generatedCopy.value)
        ElMessage.success('文案已复制到剪贴板')
    } catch (error) {
        console.error('复制失败:', error)
        ElMessage.error('复制失败，请手动选择文案复制')
    }
}
</script>

<style scoped>
.generation-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    box-sizing: border-box;
}

.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 16px 0;
}

.tabs {
    padding-bottom: 8px;
}

.content-wrapper {
    display: flex;
    height: calc(100% - 80px);
    overflow: hidden;
}

.input-panel {
    flex: 0 0 380px;
    padding: 24px 20px;
    display: flex;
    flex-direction: column;
}

.form-container {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.theme-input,
.model-select {
    width: 100%;
}

:deep(.tall-textarea .el-textarea__inner) {
    height: 186px !important;
    min-height: 186px !important;
    padding-top: 12px;
    line-height: 1.5;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-y: auto;
    resize: none;
}

.action-buttons {
    display: flex;
    margin-top: auto;
    padding-top: 20px;
    border-top: 1px solid #f1f5f9;
    gap: 12px;
}

.action-buttons .el-button {
    flex: 1;
}

.divider {
    width: 1px;
    background: #e2e8f0;
    margin: 10px 0;
}

.output-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 24px;
}

.output-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
}

.output-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #f8fafc;
    border-radius: 8px;
    padding: 20px;
}

.copy-preview {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
}

.copy-content {
    white-space: pre-wrap;
    line-height: 1.6;
    color: #333;
}
</style>